<template>
  <div class="body">
    <div class="title">
      <h2 @click="changeTab('singer')">
        歌手
        <el-icon><i-bi-arrow-right-short /></el-icon>
      </h2>
    </div>
    <div class="list">
      <div class="card" v-for="item in artistlist" :key="item.id" @click="toSinger(item.id)">
        <img :src="item.picUrl" alt="">
        <div class="info">
          <div class="artist-name">{{ item.name }}</div>
          <div class="artist-info">
            <span>MV：{{ item.musicSize }}</span>
            <span>专辑：{{ item.albumSize }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="title">
      <h2 @click="changeTab('song')">
        单曲
        <el-icon><i-bi-arrow-right-short /></el-icon>
      </h2>
    </div>
    <div class="list">
      <div class="card" v-for="item in songs" :key="item.id" @click="toTabs(item)">
        <img :src="item.albumPic" alt="">
        <div class="info">
          <div>{{ item.name }}</div>
          <div>
            <span class="vipspan" v-if="item.fee===1">vip</span>
            <span class="vipspan" v-if="item.fee===4">无版权</span>
            <span class="singers" v-for="(singer, index) in item.singer" :key="singer.id" @click.stop="toTabs(singer.id)">
              {{ singer.name }}<span v-if="index < item.singer.length - 1"> / </span>
            </span>
          </div>
        </div>
        <div class="icons">
          <el-icon @click.stop.prevent="playSong(item)">
            <i-bi-pause-fill v-if="playSongId===item.id"/>
            <i-bi-play-fill v-else/>
          </el-icon>
          <el-icon @click.stop.prevent="toTabs"><i-bi-cloud-download /></el-icon>
          <el-icon @click.stop.prevent="toTabs"><i-bi-heart /></el-icon>
          <el-icon @click.stop.prevent="toTabs"><i-bi-list /></el-icon>
        </div>
      </div>
    </div>
    <div class="title">
      <h2 @click="changeTab('playlist')">
        歌单
        <el-icon><i-bi-arrow-right-short /></el-icon>
      </h2>
    </div>
    <div class="playlist" v-loading="loading" element-loading-background="transparent">
      <div class="card" v-for="item in playlist" :key="item.id" @click="playSong(item.id)">
        <div class="bgimg" :style="{ backgroundImage: 'url(' + item.coverImgUrl + ')' }">
          <div class="overlay">
            <div class="play-count">{{ item.playCount }}</div>
            <el-icon class="play-button"><i-bi-play-circle-fill /></el-icon>
          </div>
        </div>
        <div class="info">
          <div class="song-name">{{ item.name }}</div>
          <div class="create-user">{{ item.createUser }}</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="SearchAll">
import {search} from "@/assets/apis/http"
import { reactive, watch, ref, defineEmits, computed } from "vue";
import { PlayList,Song,Singer } from "@/assets/apis/MusicDataType";
import util from "@/tools/util";
import emitter from "@/store/emitter";
import {usePlayStore} from "@/store/PlayStore";
import { useRouter } from 'vue-router'

const emit = defineEmits(['changeTab']);
const playstore = usePlayStore();
const props = defineProps<{
  keywords: string
}>();
let loading = ref<boolean>(false)
let songs = reactive<Song[]>([])
let playlist = reactive<PlayList[]>([])
let artistlist = reactive<Singer[]>([])
const router = useRouter()

function changeTab(tab:string){
  emit('changeTab', tab);
}
const playSongId = computed(()=>{
  if (playstore.isPlayed){
    return playstore.playList[playstore.playIndex].id
  }
  return 0
})
async function getList(keywords) {
  loading.value = true;
  //搜索综合，type: 搜索类型；默认为 1 即单曲 , 取值意义 : 1: 单曲, 10: 专辑, 100: 歌手, 1000: 歌单, 1002: 用户, 1004: MV, 1006: 歌词, 1009: 电台, 1014: 视频, 1018:综合, 2000:声音
  try {
    const res = await search({keywords:keywords,limit:4,type: 1018});
    console.log("综合搜索结果",res.result)
    await coverSong(res.result.song.songs.slice(0, 6));
    await coverPlaylist(res.result.playList.playLists.slice(0, 6));
    await coverArtist(res.result.artist.artists.slice(0, 2));
  } catch (error) {
    console.error("获取歌曲列表失败:", error);
  } finally {
    loading.value = false;
  }
}
function toTabs(song: Song){
  if (playstore.isPlayed){
    emitter.emit('playAudioType', 'play')
  }else{
    playstore.selectPlay([song])
  }
}
function toSinger(id: number) {
  router.push(`/singer/${id}`)
}
async function coverArtist(artists:any) {
  artistlist.push(...artists.map(artist => ({
    id: artist.id,
    name: artist.name,
    picUrl: util.formatSongsPic(artist.picUrl,100),
    albumSize: artist.albumSize,
    musicSize: artist.mvSize || 0,
    followed: artist.followed,
    alias: artist.alias[0]
  })));
}
async function coverSong(songlist:any) {
  songs.push(...songlist.map(song => ({
    id: song.id,
    name: song.name,
    albumPic: util.formatSongsPic(song.al.picUrl,100),
    album: song.al.name,
    singer: song.ar.map(({ name, id }) => ({ name, id })),
    alia: song.alia,
    fee: song.fee,            //1 vip ,0 非VIP
    no: song.no,              //1超清母带 3
    mv: song.mv,              //0代表没有mv，否则就是有
    duration: song.dt,        //持续时间
    url: "https://music.163.com/song/media/outer/url?id="+song.id+".mp3"
  })));
}

async function coverPlaylist(songlist:any) {
  playlist.push(...songlist.map(song => ({
    id: song.id,
    name: song.name,
    coverImgUrl: util.formatSongsPic(song.coverImgUrl),
    officialTags: song.officialTags.map(obj => obj).join(' / '),
    description: song.description,
    playCount: song.playCount,  //播放量
    trackCount: song.trackCount, //歌曲数量
    createUser: song.creator.nickname,
    avatarUrl: util.formatSongsPic(song.creator.avatarUrl,200),
    userId: song.creator.userId
  })));
}

function playSong(song){
  if (playstore.isPlayed){
    emitter.emit('playAudioType', 'play')
  }else{
    playstore.selectPlay([song])
  }
}
watch(() => props.keywords, (newKeywords) => {
  songs.length=0
  playlist.length=0
  getList(newKeywords);
});
getList(props.keywords)
</script>
<style scoped lang="scss">
.body{
  margin: 20px;
  .title h2{
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 4px;
    &:hover {
      color: var(--el-color-primary);
      .el-icon {
        color: var(--el-color-primary);
      }
    }
    .el-icon {
      margin-top: 2px;
    }
  }
  .list{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .card{
      display: flex;
      width: calc(50vw - 200px);
      gap: 20px;
      border-radius: 10px;
      padding: 8px;
      align-items: center;
      flex-direction: row;
      justify-content: flex-start;
      &:hover {
        background-color: var(--my-bg-menu-hover);
        cursor: pointer;
        .icons {
          display: block;
        }
      }
      img {
        width: 65px;
        border-radius: 10px;
      }
      .info{
        display: flex;
        flex-direction: column;
        height: 100%;
        justify-content: space-around;
        .artist-name {
          font-size: 14px;
          font-weight: 500;
          margin-bottom: 6px;
        }
        .artist-info {
          font-size: 12px;
          color: var(--el-text-color-placeholder);
          span {
            margin-right: 12px;
            &:last-child {
              margin-right: 0;
            }
          }
        }
        .vipspan{
          color: var(--el-color-error);
          border: solid 1px var(--el-color-error);
          margin-right: 5px;
        }
      }
      .icons {
        display: none;
        font-size: 20px;
        margin-left: auto;
        color: var(--el-text-color-placeholder);
        .el-icon{
          margin-right: 8px;
          &:hover{
            color: var(--el-text-color-primary);
          }
        }
      }
    }
  }

  .playlist{
    display: flex;
    flex-wrap: nowrap;
    overflow: hidden; /* 隐藏多余的内容 */
    .card {
      flex: 0 0 auto;
      width: 250px; /* 根据需要调整宽度 */
      margin: 10px;
      cursor: pointer;
    }

    .bgimg {
      position: relative;
      height: 150px; /* 根据需要调整高度 */
      background-size: cover;
      background-position: center;
    }

    .overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white; /* 根据需要调整文本颜色 */
    }

    .play-button {
      width: 30px; /* 根据需要调整按钮大小 */
      height: 30px;
      margin-right: 10px;
    }

    .play-count {
      font-size: 16px; /* 根据需要调整字体大小 */
    }

    .info {
      padding: 10px;
    }

    .song-name {
      font-weight: bold;
    }

    .create-user {
      color: gray; /* 根据需要调整颜色 */
    }
  }
}
</style>
